package com.service;

import org.springframework.util.StringUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketClientService {
    private static SocketClientService socketInstance;
    private String message;

    private  Socket socket;

    private SocketClientService() throws Exception{
     socket = new Socket("127.0.0.1",1001);
        System.out.println("连接serverSocket,"+1001+"端口");

   }
   public synchronized static SocketClientService getSocket() throws Exception {
       if(socketInstance == null){
           socketInstance = new SocketClientService();
       }
       return socketInstance;
   }



    /**
     * 读取socket消息
     * @throws Exception
     */
    public void socketRed() throws Exception {


            BufferedReader bufferedReader = null;
            try {
                 bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String message = bufferedReader.readLine();
                if (!StringUtils.isEmpty(message)) {
                    this.message = message;
                    System.out.println("服务端消息:" + message);
                }
            }catch (Exception e){
                bufferedReader.close();
                socket.close();

            }



    }

    /**
     * 发送socket消息
     * @param message
     */
    public void socketSend(String message) {


            PrintWriter printWriter = null;
            try {

                printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);


                    printWriter.print(message);


            } catch (Exception e) {
                e.printStackTrace();

                printWriter.close();
                try {
                    this.socket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

    }
    public void socketClose() throws Exception{
        socket.close();
    }

    /**
     * 校验socket
     * @return
     */
    public boolean socketVerity() throws Exception{
        socketRed();
        if(this.socket.isClosed()){
            throw new RuntimeException("socket error");
        }
        if(!this.message.equals("ok")){
           throw new RuntimeException("orther socket eroor");
        }
        return true;

    }

}
